package com.kgcx.dbutils.configure;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ObjectUtils;

import com.kgcx.dbutils.core.interceptor.MybatisInterceptor;

/**
 * @author 袁进勇
 */
@Configuration
@MapperScan(basePackages = { "com.kgcx.**.mapper.**" }, sqlSessionTemplateRef = "defaultSqlSessionTemplate")
public class DefaultMybatisConfiguration {
    @Value("${kgcx.mybatis.mapper.typeAliasesPackage:com.kgcx.**.domain}")
    private String typeAliasesPackage;
    @Value("${kgcx.mybatis.mapper.mapperLocations:classpath:/com/kgcx/**/mapper/*Mapper.xml}")
    private String mapperLocations;

    @Autowired(required = false)
    private MybatisInterceptor[] interceptors;
    @Autowired(required = false)
    private DatabaseIdProvider databaseIdProvider;

    @Bean(name = "defaultSqlSessionFactory")
    // public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("defaultDataSource") DataSource dataSource)
    public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("druidDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            factory.setPlugins(this.interceptors);
        }
        if (this.databaseIdProvider != null) {
            factory.setDatabaseIdProvider(this.databaseIdProvider);
        }

        factory.setTypeAliasesPackage(typeAliasesPackage);
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));

        return factory.getObject();
    }

    @Bean(name = "defaultSqlSessionTemplate")
    public SqlSessionTemplate defaultSqlSessionTemplate(
            @Qualifier("defaultSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
